﻿#region License

// Copyright (c) 2009, Bill O'Neill (william.w.oneill@gmail.com)
// All rights reserved.
// 
// Redistribution and use in source and binary forms, with or without 
// modification, are permitted provided that the following conditions 
// are met:
// 
// 1. Redistributions of source code must retain the above copyright 
// notice, this list of conditions and the following disclaimer.
// 
// 2. Redistributions in binary form must reproduce the above copyright 
// notice, this list of conditions and the following disclaimer in the 
// documentation and/or other materials provided with the distribution.
// 
// 3. Neither the name of Focal Point Technology Solutions, LLC nor 
// the names of its contributors may be used to endorse or promote 
// products derived from this software without specific prior written 
// permission.
// 
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND 
// CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR 
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH 
// DAMAGE.

#endregion

using System.Diagnostics;
using System.IO.Ports;

namespace X10d.Interface.States
{
	/// <summary>
	/// Base class for request manager states
	/// </summary>
	internal abstract class PortStateBase : IPortState
	{
		protected const byte InterfaceReady = 0x55;
		protected const byte OKForTransmission = 0x00;
		protected const byte PCReady = 0xc3;
		protected const byte PollSignal = 0x5a;
		protected const byte InterfaceStatusRequest = 0x8b;
		protected const byte TimeUpdate = 0x9b;
		protected const byte TimeUpdateRequest = 0xa5;
		protected const byte Address = 0x04;
		protected const byte Function = 0x06;

		#region IPortState Members

		/// <summary>
		/// Handles new data from the serial port
		/// </summary>
		/// <remarks>
		/// Invokes the template method <see cref="DoHandleNewBuffer"/> on the concrete classes
		/// when new data arrives
		/// </remarks>
		/// <param name="requestManager">
		/// Reference to the request manager
		/// </param>
		public void HandleNewData(IRequestManager requestManager)
		{
			int bytesAvailable = requestManager.Port.BytesToRead;

			if ( bytesAvailable > 0 )
			{
				var buffer = new byte[bytesAvailable];

				requestManager.Port.Read(buffer, 0, bytesAvailable);

				Log.Info("New data received");
				Log.WriteBuffer(buffer);

				switch (buffer[0])
				{
					case PollSignal:
						// Poll signal from the device? If so, switch to the poll signal response state.
						// Poll signals arrive at various times. This keeps duplicate code in one place.
						requestManager.TransitionToState( new HandlePollSignalState() );
						break;

					case TimeUpdateRequest:
						// Time update request from the interface? Respond with current time.
						requestManager.TransitionToState( new HandleTimeUpdateRequest() );
						break;

					default:
						// Defer to the concrete instance to handle the data we cannot handle
						DoHandleNewBuffer(requestManager, buffer);
						break;
				}
			}
		}

		/// <summary>
		/// Handles the state arrival notification from the request manager
		/// </summary>
		/// <param name="requestManager">
		/// Reference to the request manager
		/// </param>
		public virtual void HandleArrive(IRequestManager requestManager)
		{
		}

		#endregion

		protected abstract void DoHandleNewBuffer(IRequestManager requestManager, byte[] newBuffer);
	}
}